package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private CategoryService categoryService;
    @Reference
    private SkuService skuService;

    public List<Map<String, Object>> findCartList(String username) {

        List<Map<String, Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);

        //如果查询不到，返回一个"{}"
        if (cartList == null) {
            return new ArrayList<Map<String, Object>>();
        }

        return cartList;
    }

    public void saveGoodsToCart(String username, String skuId, Integer num) {
        //遍历购物车，检查是否已经存在商品
        List<Map<String, Object>> cartList = findCartList(username);

        boolean flag = false;
        for (Map<String, Object> map : cartList) {
            //获取每一个购物车明细
            OrderItem orderItem = (OrderItem) map.get("item");

            if (orderItem.getSkuId().equals(skuId)) {
                //说明商品存在，只需要修改数量
                Integer weight = orderItem.getPrice() / orderItem.getNum();//计算平均价格
                if (orderItem.getNum() <= 0) {
                    cartList.remove(map);
                    flag = true;
                    break;
                }

                orderItem.setNum(orderItem.getNum() + num);//重新计算数量
                orderItem.setMoney(orderItem.getNum() * orderItem.getPrice());//重新计算价格
                orderItem.setWeight(orderItem.getNum() * weight);//重新计算重量

                if (orderItem.getNum() <= 0) {//可以实现数量删减
                    cartList.remove(map);
                }
                flag = true;
                break;
            }
        }
        if (flag == false) {
            //说明不存在商品，需要新增
            Sku sku = skuService.findById(skuId);

            if (sku == null) {
                throw new RuntimeException("商品不存在");
            }

            if (!"1".equals(sku.getStatus())) {
                throw new RuntimeException("商品状态错误");
            }

            if (num <= 0) {
                throw new RuntimeException("商品数量异常");
            }

            OrderItem orderItem = new OrderItem();

            //设置分类信息
            orderItem.setCategoryId3(sku.getCategoryId());//设置3级分类id

            Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            if (category3 == null) {
                category3 = categoryService.findById(sku.getCategoryId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(), category3);
            }
            orderItem.setCategoryId2(category3.getParentId());

            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());
            if (category2 == null) {
                category2 = categoryService.findById(category3.getParentId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getParentId(), category2);
            }
            orderItem.setCategoryId1(category2.getParentId());


            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setImage(sku.getImage());
            orderItem.setMoney(sku.getPrice() * num);//重新计算金额

            if (sku.getWeight() == null) {
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight() * num);//重新计算重量

            Map map = new HashMap();
            map.put("item", orderItem);
            map.put("checked", true);

            cartList.add(map);
        }

        //存入缓存
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
    }

    public boolean updateChecked(String username, String skuId, boolean checked) {
        //获取购物车信息
        List<Map<String, Object>> cartList = findCartList(username);

        boolean isOk = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if(orderItem.getSkuId().equals(skuId)){
                map.put("checked",checked);
                isOk = true;
                break;
            }
        }

        if(isOk){
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        }

        return isOk;
    }

}
